/**
 * Copyright (c) 2007-2008 Nearchos Paspallis
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * AspectSense
 *
 * Middleware for annotation-based, context-aware and adaptive services for
 * mobile and ubiquitous computing
 *
 * This project is an open-source effort, initiated by Nearchos Paspallis as
 * part of his PhD work at the University of Cyprus (http://www.ucy.ac.cy).
 *
 * More information about the project is available at "http://aspectsense.org".
 */

package org.aspectsense.gui.desktop;

import org.aspectsense.framework.Main;
import org.aspectsense.framework.CoreServices;
import org.aspectsense.coreservices.AdaptationService;
import org.aspectsense.coreservices.ContextService;
import org.aspectsense.context.events.ContextChangedEvent;
import org.aspectsense.context.*;
import org.aspectsense.gui.util.AboutFrame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;

/**
 * @author Nearchos Paspallis [nearchos@cs.ucy.ac.cy]
 *         Date: Jan 14, 2008
 *         Time: 3:04:35 PM
 */
public class UserPreferencesFrame
{
    public static final String TITLE = "AspectSense " + Main.COPYRIGHT + " - User Preferences";

    public static final Dimension PREFERRED_FRAME_SIZE = new Dimension(500, 300);

    private static JFrame userPreferencesFrame;

    static final JPanel slidersPanel = new JPanel(new BorderLayout());

    static public void show()
    {
        synchronized(UserPreferencesFrame.class)
        {
            if(userPreferencesFrame == null)
            {
                userPreferencesFrame = new JFrame(TITLE) {
                    public Dimension getPreferredSize() {
                        return PREFERRED_FRAME_SIZE;
                    }
                    public String toString() {
                        return "User preferences frame";
                    }
                };

                final JButton okButton = new JButton("OK");
                okButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e)
                    {
                        applyUserPreferences();
                        hide();
                    }
                });
                final JButton applyButton = new JButton("Apply");
                applyButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e)
                    {
                        applyUserPreferences();
                    }
                });
                final JButton cancelButton = new JButton("Cancel");
                cancelButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e)
                    {
                        hide();
                    }
                });

                final JButton refreshButton = new JButton("Refresh");
                refreshButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e)
                    {
                        refresh();
                    }
                });

                final JLabel topLabel = new JLabel("  User preferences");
                topLabel.setForeground(new Color(0, 0, 128));

                final JPanel topPanel = new JPanel(new BorderLayout());
                topPanel.add(topLabel, BorderLayout.WEST);
                topPanel.add(refreshButton, BorderLayout.EAST);

                final JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
                buttonsPanel.add(okButton);
                buttonsPanel.add(applyButton);
                buttonsPanel.add(cancelButton);

                final JPanel mainPanel = new JPanel(new BorderLayout());

                mainPanel.add(topPanel, BorderLayout.NORTH);
                mainPanel.add(new JScrollPane(slidersPanel), BorderLayout.CENTER);
                mainPanel.add(buttonsPanel, BorderLayout.SOUTH);

                userPreferencesFrame.add(mainPanel);

                userPreferencesFrame.pack();
                // center
                final Dimension screeDimension = Toolkit.getDefaultToolkit().getScreenSize();
                userPreferencesFrame.setLocation(
                        (int) (screeDimension.getWidth() - userPreferencesFrame.getWidth()) / 2,
                        (int) (screeDimension.getHeight() - userPreferencesFrame.getHeight()) / 2);
            }

            refresh();

            userPreferencesFrame.setVisible(true);
        }
    }

    static private void refresh()
    {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                slidersPanel.removeAll();
                slidersPanel.add(getUserPreferencesPanel(), BorderLayout.CENTER);
                slidersPanel.repaint();
                userPreferencesFrame.repaint();
                userPreferencesFrame.validate();
            }
        });
    }

    static public void hide()
    {
        userPreferencesFrame.setVisible(false);
    }

    static private final AdaptationService adaptationService
            = CoreServices.getAdaptationService();

    static private final ContextService contextService
            = CoreServices.getContextService();

    static private final Map<String, JSlider> userPreferences
            = new HashMap<String, JSlider>();

    static private JPanel getUserPreferencesPanel()
    {
        final Map<String, Boolean> endUserServiceAvailability
                = adaptationService.getEndUserServiceAvailability();

        final Map<String, Double> userNeededServices
                = adaptationService.getUserNeededServices();

        final Set<String> availableEndUserServiceIDs = endUserServiceAvailability.keySet();
        final int numOfServices = endUserServiceAvailability.size();

        userPreferences.clear();
        for(final String availableEndUserServiceID : availableEndUserServiceIDs)
        {
            final JSlider slider = createSlider();

            // convert double value [0.0, 1.0] to integer value [0, 100]
            final int value = (int) (100 * userNeededServices.get(availableEndUserServiceID));
            slider.setValue(value);
            userPreferences.put(availableEndUserServiceID, slider);
        }

        final JPanel userPreferencesPanel = new JPanel(new GridLayout(0, 1, 0, 4)) {
            public Insets getInsets()
            {
                return new Insets(8, 8, 8, 8);
            }
        };

        userPreferencesPanel.setBorder(BorderFactory.createLoweredBevelBorder());
        userPreferencesPanel.setBackground(Color.WHITE);

        for(final String availableEndUserServiceID : availableEndUserServiceIDs)
        {
            final JSlider slider = userPreferences.get(availableEndUserServiceID);

            final boolean enabled = endUserServiceAvailability.get(availableEndUserServiceID);
            slider.setEnabled(enabled);

            final JPanel panel = new JPanel(new BorderLayout());
            panel.setOpaque(false);
            final String borderTitle = availableEndUserServiceID + (enabled ? "" : " (unavailable)");
            panel.setBorder(BorderFactory.createTitledBorder(borderTitle));
            panel.setEnabled(enabled);

            panel.add(slider, BorderLayout.CENTER);

            userPreferencesPanel.add(panel);
        }

        if(numOfServices < 5)
        {
            for(int i = 0; i < 5 - numOfServices; i++)
            {
                userPreferencesPanel.add(new JLabel());
                userPreferencesPanel.add(new JLabel());
            }
        }

        return userPreferencesPanel;
    }

    static private void applyUserPreferences()
    {
        final Map<String, Double> userNeededServices
                = adaptationService.getUserNeededServices();

        final Map<ContextType, ContextValue> contextChanges
                = new HashMap<ContextType, ContextValue>();

        final ContextModel contextModel = contextService.getContextModel();

        final Set<String> availableEndUserServiceIDs = userNeededServices.keySet();
        for(final String availableEndUserServiceID : availableEndUserServiceIDs)
        {
            final JSlider slider = userPreferences.get(availableEndUserServiceID);
            final double value = slider.getValue() / 100d;

            if(value != userNeededServices.get(availableEndUserServiceID))
            {
                final String contextTypeID = DefaultContextType.USER_PREFERENCES_CONTEXT_TYPE.toString()
                                + "." + availableEndUserServiceID;
                final ContextType contextType
                        = contextModel.getContextType(contextTypeID);
                final ContextValue contextValue
                        = new DefaultDoubleContextValue(value);
                contextChanges.put(contextType, contextValue);
            }
        }

        if(!contextChanges.isEmpty())
        {
            final Query query = new DefaultQuery(QueryType.CONTEXT_UPDATE, DefaultContextType.USER_PREFERENCES_CONTEXT_TYPE);
            final QueryResults queryResults = new QueryResults(contextChanges);
            final ContextChangedEvent contextChangedEvent
                    = new ContextChangedEvent(userPreferencesFrame, query, queryResults);

            contextService.raiseEvent(contextChangedEvent);
        }
    }

    static private JSlider createSlider()
    {
        final JSlider slider = new JSlider(JSlider.HORIZONTAL);

        slider.setMinimum(0);
        slider.setMaximum(100);
        slider.setPaintLabels(true);
        slider.setMinorTickSpacing(10);
        slider.setPaintTicks(true);
        slider.setSnapToTicks(true);
        slider.setOpaque(false);

        final Dictionary<Integer, JLabel> dictionary = new Hashtable<Integer, JLabel>(6);
        final Double [] steps = { 0.0d, 0.2d, 0.4d, 0.6d, 0.8d, 1.0d};
        for(final Double step : steps)
        {
            final int value = (int) (100 * step);
            dictionary.put(value, new JLabel(Double.toString(step)));
        }
        slider.setLabelTable(dictionary);

        return slider;
    }
}